<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/27 0027
 * Time: 下午 8:12
 */
namespace app\api\service;

use app\admin\model\Store;
use app\admin\model\Ticket;
use app\admin\model\Userbuyticket;
use app\common\Helper;
use app\common\model\User;
use app\lib\exception\PayException;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class Pay{

    private $userId;
    private $storeId;
    private $ticketId;
    private $orderId;

    function __construct($param)
    {
        $this->userId = $param['userId'];
        $this->storeId = $param['storeId'];
        $this->ticketId = $param['ticketId'];
    }


//    private function updateUserGroupStatus($spellGroupId,$orderID){
//        $groupproduct = Groupproduct::get($spellGroupId);
//        $chentuannum = $groupproduct->groupSuccCount;
//        $timeh = $groupproduct->groupDateStr;
//        $groupdetail = Groupdetail::where('orderId',$orderID)->find();
//        if($groupdetail->userId == $groupdetail->originator){
//            $endDate = time()+$timeh*60;
//        }else{
//            $tuanzhang = Groupdetail::get($groupdetail->unigroupId);
//            $endDate = $tuanzhang->endDate;
//        }
//        $goups = Groupdetail::where('unigroupId',$groupdetail->unigroupId)->lock(true)->select();
//        if(count($goups) < $chentuannum){
//            $groupdetail->endDate = $endDate;
//            $groupdetail->status = 1;
//            $groupdetail->isActive = 1;
//            $groupdetail->save();
//        }elseif (count($goups) == $chentuannum){
//            //拼团成功  此团的所有参与者状态都改变
//            $allgroups = Groupdetail::where('unigroupId',$groupdetail->unigroupId)->select();
//            $list = [];
//            foreach ($allgroups as $value){
//                array_push($list,['id'=>$value['id'],'status'=>2,'isActive'=>1,'endDate'=>$endDate]);
//            }
//            (new Groupdetail())->saveAll($list);
//        }else{
//
//        }
//    }

//    private function insertOrderCommiss($saleRuleId,$orderId){
//        $sale = Salerule::get($saleRuleId);
//        $order = OrderModel::get($orderId);
//        $storeId = $order->storeId;
//        $proportion = $sale->value1;
//        $user = User::get($order->createUser);
//        $shangjiId = $user->chiefUserId;
//        if($this->isCheckFs($order->createUser,$shangjiId)){
//            $ordercommission = new Ordercommission();
//            $ordercommission->orderId = $orderId;
//            $ordercommission->saleruleId = $saleRuleId;
//            $ordercommission->proportion = $proportion;
//            $ordercommission->userId = $order->createUser;
//            $ordercommission->shangjiId = $shangjiId;
//            $ordercommission->total = $order->total;
//            $ordercommission->storeId = $storeId;
//            $ordercommission->save();
//        }
//    }

//    private function isCheckFs($userid,$shangjiId){
//        $user = User::get($userid);
//        $shangji = User::get($shangjiId);
//        if($user->tenantId == $shangji->tenantId){
//            return true;
//        }
//        return false;
//
//    }

//    private function updateOrderStatus($orderID,$ordertype,$success){
//        $paytime = date('Y-m-d H:i:s',time());
//        if($success && $ordertype==DictConstant::ORDER_TYPE_ONLINE){
//            $status = DictConstant::OrderPendingDelivery;
//        }
//        if($success && $ordertype==DictConstant::ORDER_TYPE_UNDERLINE){
//            $status = DictConstant::Order_Unconsumed;
//        }
//        if(!$success){
//            $status = DictConstant::PAID_BUT_OUT_OF;
//        }
//        OrderModel::where('id','=',$this->orderID)->update(['status'=>$status,'payMethod'=>1,'payDate'=>$paytime]);
//        $Orderproductdetail = new Orderproductdetail();
//        $orderpro = $Orderproductdetail->where('orderId',$orderID)->select();
//        $list = [];
//        foreach ($orderpro as $value){
//            array_push($list,['id'=>$value['id'],'oldStatus'=>$status]);
//        }
//        $Orderproductdetail->saveAll($list);
//
//    }

//    private function reduceStock($stockStatus){
//        foreach ($stockStatus['pStatusArray'] as $singlePSstatus){
//            //storeCount
//            if(isset($singlePSstatus['specid'])){
//                Productspecgroups::where('id','=',$singlePSstatus['specid'])->setDec('storeCount',$singlePSstatus['counts']);
//            }else{
//                Product::where('id','=',$singlePSstatus['id'])->setDec('storeCount',$singlePSstatus['counts']);
//            }
//        }
//    }


    public function pay(){

        $TicketModel = new Ticket();
        $ticket = $TicketModel->getTicket($this->ticketId);
        return show(config('status.SUCCESS_STATUS'),'ok',$this->makeWxPreOrder($ticket->buyTicketMoney,$ticket->name));

    }

    /**
     * 生成微信预订单
     * @param $totalPrice
     * @return array
     */
    private function makeWxPreOrder($totalPrice,$productName){
        $openid = User::getopenId($this->userId);
        $orderNO = $this->makeOrderNo();
        $wxOrderData = new \WxPayUnifiedOrder();
        $wxOrderData->SetOut_trade_no($orderNO);
        $wxOrderData->SetTrade_type('JSAPI');
        $wxOrderData->SetTotal_fee($totalPrice);
        $wxOrderData->SetBody($productName);
        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetNotify_url(config('wx.pay_back_url'));

        $orderdata['totalPrice'] = $totalPrice;
        $orderdata['orderNo'] = $orderNO;

        return $this->getPaySignature($wxOrderData,$orderdata);

    }

    /**
     * 请求微信统一下单接口返回给客户端一组支付参数
     * @param $wxOrderData
     * @return \成功时返回，其他抛异常
     */
    private function getPaySignature($wxOrderData,$orderdata){
        $wxOrder = \WxPayApi::unifiedOrder($wxOrderData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS'){
            Log::record($wxOrder,'error');
            Log::record('获取预支付订单失败','error');
        }else{
            //插入预订单(未支付)
            $data['userId'] = $this->userId;
            $data['storeId'] = $this->storeId;
            $data['ticketId'] = $this->ticketId;
            $data['orderNo'] = $orderdata['orderNo'];
            $data['totalPrice'] = $orderdata['totalPrice'];
            $this->insertOrder($data);
        }
        if($wxOrder['return_code'] == 'FAIL'){
            throw new PayException([
                'msg' => '商户号或者支付秘钥异常'
            ]);
        }
        $this->recordPreOrder($wxOrder);
        return $this->sign($wxOrder);
    }

    /**
     * 生成签名
     * @param $wxOrder
     * @return array
     */
    private function sign($wxOrder){
        $jsApiPayData = new \WxPayJsApiPay();
        $jsApiPayData->SetAppid(config('wx.app_id'));
        $jsApiPayData->SetTimeStamp((string)time());
        $jsApiPayData->SetNonceStr(Helper::getUUID());
        $jsApiPayData->SetPackage('prepay_id='.$wxOrder['prepay_id']);
        $jsApiPayData->SetSignType('md5');
        $sign = $jsApiPayData->MakeSign();
        $rowValues = $jsApiPayData->GetValues();
        $rowValues['paySign'] = $sign;
        unset($rowValues['appId']);
        return $rowValues;
    }

    private function recordPreOrder($wxOrder){
        Userbuyticket::where('id','=',$this->orderId)->update(['prepay_id'=>$wxOrder['prepay_id']]);
    }


    private function insertOrder($data){
        $Userbuyticket = new Userbuyticket();
        $Userbuyticket->id = Helper::getUUID();
        $Userbuyticket->userId = $data['userId'];
        $Userbuyticket->storeId = $data['storeId'];
        $Userbuyticket->ticketId = $data['ticketId'];
        $Userbuyticket->storeName = $this->getstoreName($data['storeId']);
        $Userbuyticket->money = $data['totalPrice'];
        $Userbuyticket->orderNo = $data['orderNo'];
        $Userbuyticket->type = 1;
        $Userbuyticket->save();
        $this->orderId = $Userbuyticket->id;
    }


    private function getstoreName($storeId){
        $Store = Store::get($storeId);
        return $Store->name;
    }

    /**
     * 生成订单号
     * @return string
     */
    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M');
        $orderSn =
            $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }
}